<template>
  <div class="app-container">
    <el-input
      v-model="listQuery.search"
      placeholder="请输入角色名"
      style="width: 150px;"
      class="filter-item"
      @keyup.enter.native="handleFilter"
    />
    <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    <el-button v-if="create" type="primary" @click="handleAdd">新建角色</el-button>
    <el-table
      v-loading="listLoading"
      :data="modelList"
      element-loading-text="Loading"
      style="width: 100%;margin-top:30px;"
      border
    >
      <!-- <el-table-column label="ID" align="center" prop="Id">
        <template slot-scope="scope">
          <span>{{ scope.row.Id }}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="角色名称" width="220">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="描述">
        <template slot-scope="scope">{{ scope.row.description }}</template>
      </el-table-column>
      <el-table-column label="添加日期" prop="CreateTime" align="center" width="160" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" align="center" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.editTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="update" type="primary" size="small" @click="handleEdit(scope)">修改</el-button>
          <el-button v-if="del" type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getRoles"
    />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改角色':'新建角色'">
      <el-form :model="model" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="model.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="model.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :default-expand-all="expandAll"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            node-key="path"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmHandle">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 引入分页组件
import { deepClone, parseTime } from '@/utils'
import { getModelList, addModel, deleteModel, updateModel } from '@/api/role/role.js'
import { asyncRoutes } from '@/utils/routes.js'
// import { getChildFunctions } from '@/utils/auth.js'
/**
 * 合并数组
 * [...constantRoutes, ...asyncRoutes] 它们的成员都是对原数组成员的引用，这就是浅拷贝。如果修改了原数组的成员，会同步反映到新数组。
 */
const routes = asyncRoutes
const defaultModel = {
  id: '',
  name: '',
  routes: []
}
/* const functionsPath = {
  create: '/information/role/create',
  update: '/information/role/update',
  delete: '/information/role/delete'
} */
export default {
  filters: {
    parseTime
  },
  components: { Pagination },
  data () {
    return {
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        search: undefined
      },
      childFunctions: '',
      create: true, // 添加按钮权限 默认有
      update: true, // 修改
      del: true, // 删除
      model: Object.assign({}, defaultModel),
      routes: routes,
      modelList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      expandAll: true,
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {
    routesData () {
      return this.routes
    }
  },
  created () {
    // this.getChildFun()
    // 获取所有的角色
    this.getRoles()
  },
  methods: {
    // 获取按钮权限，每次进入页面的时候，都将权限存在了cookies中，在created钩子中取出判断即可
    /* getChildFun () {
      const aa = getChildFunctions()
      this.childFunctions = aa
      if (aa.indexOf(functionsPath.create) === -1) {
        this.create = false
      }
      if (aa.indexOf(functionsPath.delete) === -1) {
        this.del = false
      }
      if (aa.indexOf(functionsPath.update) === -1) {
        this.update = false
      }
    }, */
    async getRoles () {
      this.listLoading = true
      const res = await getModelList(this.listQuery)
      this.modelList = res.data
      this.total = res.totalRecord
      // 这里只是为了模拟请求的时间
      setTimeout(() => {
        this.listLoading = false
      }, 0.5 * 1000)
    },
    handleFilter () {
      this.listQuery.currentPage = 1
      this.getRoles()
    },
    handleAdd () {
      this.model = Object.assign({}, defaultModel)
      // 添加角色的时候都不选中
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit (scope) {
      // console.log(scope)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.model = deepClone(scope.row)
      this.$nextTick(() => {
        const routes = this.model.routes
        // 通过节点设置已有的权限
        this.$refs.tree.setCheckedNodes(routes)
        // 设置节点的选中状态不影响其父节点和子节点
        this.checkStrictly = false
      })
    },
    handleDelete ({ $index, row }) {
      this.$confirm('确认删除此角色?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deleteModel(row.id)
          if (res.msg === 'Success') {
            this.getRoles()
            this.$message({
              message: '删除成功!',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    async confirmHandle () {
      const isEdit = this.dialogType === 'edit'
      /* // 获取半选节点
      const checkedParentNodes = this.$refs.tree.getHalfCheckedNodes()
      // 获取选中的节点
      const checkedChildNodes = this.$refs.tree.getCheckedNodes()
      // this.model.routes = checkedParentNodes.concat(checkedChildNodes)
      // 将半选节点和选中的节点合并起来
      this.model.routes = deepClone([...checkedParentNodes, ...checkedChildNodes]) */
      if (isEdit) {
        const res = await updateModel(this.model)
        this.dialogVisible = false
        if (res.msg === 'Success') {
          this.getRoles()
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      } else {
        const res = await addModel(this.model)
        this.dialogVisible = false
        if (res.msg === 'Success') {
          this.getRoles()
          this.$message({
            message: '添加成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }
    }
  }
}
</script>

